import React, { useRef } from 'react';
import { Box } from '@mui/material';
import { motion, useInView } from 'framer-motion';

let sectionCounter = 0;

export const RealEstatePageReveal = (props) => {
  const {
    backgroundColor = null,
    backgroundColorInner = '#ffffff',
    borderRadiusInner = 12,
    zIndex = 1000,
    zIndexInner = 1300,
    marginY = 0,
    paddingY = 0,
    paddingX = 0,
    text,
    useInnerBox = true,
    innerBoxSx = {},
    direction = 'auto',
    ...otherProps
  } = props;

  const sectionRef = useRef(null);
  const isInView = useInView(sectionRef, {
    amount: 0.3,
    once: false,
  });

  let fromLeft;
  if (direction === 'auto') {
    const currentSection = sectionCounter++;
    fromLeft = currentSection % 2 === 0;
  } else if (direction === 'random') {
    fromLeft = Math.random() < 0.5;
  } else {
    fromLeft = direction === 'left';
  }

  const variants = {
    hidden: {
      x: fromLeft ? '-100vw' : '100vw',
      opacity: 0,
      borderRadius: borderRadiusInner,
    },
    visible: {
      x: 0,
      opacity: 1,
      borderRadius: borderRadiusInner,
      transition: {
        type: 'tween',
        duration: 0.6,
        ease: 'easeOut',
      },
    },
    exit: {
      x: fromLeft ? '100vw' : '-100vw',
      opacity: 0,
      borderRadius: borderRadiusInner,
      transition: {
        type: 'tween',
        duration: 0.6,
        ease: 'easeIn',
      },
    },
  };

  const defaultShadow = '0px 4px 12px rgba(0, 0, 0, 0.15)';

  return (
    <Box
      ref={sectionRef}
      sx={{
        marginY,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor,
        width: '100%',
        overflow: 'hidden',
        zIndex,
      }}
      {...otherProps}
    >
      <motion.div
        initial="hidden"
        animate={isInView ? 'visible' : 'exit'}
        variants={variants}
        style={{
          borderRadius: borderRadiusInner,
          overflow: 'hidden',
          width: useInnerBox ? 'auto' : '100%',
        }}
      >
        {useInnerBox ? (
          <Box
            sx={{
              width: {
                xs: '100%',
                sm: 600,
                md: 960,
                lg: 1280,
                xl: 1920,
              },
              paddingY,
              paddingX,
              backgroundColor: backgroundColorInner,
              borderRadius: borderRadiusInner,
              boxShadow: defaultShadow,
              zIndex: zIndexInner,
              ...innerBoxSx,
            }}
          >
            {text}
          </Box>
        ) : (
          <Box
            sx={{
              paddingY,
              paddingX,
              borderRadius: borderRadiusInner,
            }}
          >
            {text}
          </Box>
        )}
      </motion.div>
    </Box>
  );
};

export default RealEstatePageReveal;